<?php

namespace App\Http\Controllers\Guard\Dev;

use App\Http\Controllers\Common\GuardController;
use App\Models\Constant\DevConstant;
use App\Models\Dev\DevType;
use Illuminate\Http\Request;

class DevTypeController extends GuardController{


    public function __construct() {
        $this->instance = new DevType();
    }

    public function lst(Request $request) {

        if($request->has('all')){
            $records = $this->instance->newQuery()->get(['id as value','business_type','name','self_code']);
            foreach ($records as $record) {
                $record->label = "$record->business_name---$record->name---$record->self_code";
            }
            return responseSuccess($records->toArray());
        }

        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',50);
        $conditions = $request->input();
        $records = $this->instance->getLst($conditions)->paginate($pageSize,$this->getCol,'page',$page);
        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {
        $info = $request->input();

        $this->validate($request, [
            'self_code'=>'required',
            'name'=>'required'
        ],[],[
            'self_code'=>'自编码',
            'name'=>'名称'
        ]);

        if($this->instance->newQuery()->where('self_code',$info['self_code'])->exists())
            return responseFail($info['self_code'].' 已经存在！');

        $record = $this->instance->updateOrCreate(['id'=>$info['id']??0],$info);
        return responseSuccess($record->toArray(),1);
    }

    public function business(Request $request){
        $temp = [];
        foreach (DevConstant::MAP_BUSINESS_NAME as $k=>$v) {
            $temp[] = compact('k','v');
        }
        return responseSuccess($temp);
    }

    public function change(Request $request) {
        $id = $request->input('id',0);
        $status = $request->input('status');
        $this->instance->changeColById($id, compact('status'));
        return responseSuccess();
    }

    public function detail(Request $request){
        $id = $request->input('id',0);
        $record = $this->instance->getRecordById($id);
        return responseSuccess($record->toArray(),1);
    }
}
